package com.dq.context.listener.user;

import com.dq.context.event.OrderEvent;
import com.dq.domain.orders.Orders;
import com.dq.domain.orders.UserOrder;
import com.dq.domain.org.Org;
import com.dq.domain.record.ProfitRecord;
import com.dq.domain.setup.ReturnCommission;
import com.dq.domain.sys.user.user.base.SysUser;
import com.dq.repository.order.UserOrderRepository;
import com.dq.repository.set.ReturnCommissionRepository;
import com.dq.repository.record.ProfitRecordRepository;
import com.dq.repository.user.IntegralRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

/**
 * @Author luchangtong
 * @Date 2019/11/28 17:45
 */
@Component
public class OrderEventListener implements ApplicationListener<OrderEvent>{

    @Autowired
    protected ReturnCommissionRepository returnCommissionRepository;
    @Autowired
    protected ProfitRecordRepository profitRecordRepository;
    @Autowired
    protected IntegralRepository integralRepository;
    @Autowired
    protected UserOrderRepository userOrderRepository;

    @Override
    @Async
    public void onApplicationEvent(OrderEvent orderEvent) {
        ReturnCommission((Orders) orderEvent.getSource());
    }

    /**
     * 分润
     */
    public void ReturnCommission(Orders order){
        UserOrder userOrder = (UserOrder) order;
        SysUser user = userOrder.getWxUser();
        //推荐人
        SysUser inviteUser =user.getInviteUser();
        //提成比例
        ReturnCommission returnCommission = returnCommissionRepository.getBySysDeptAndDeletedFalseAndProportionType((Org) inviteUser.getSection(), ReturnCommission.ProportionType.rakeBack);
        ProfitRecord profitRecord = new ProfitRecord();
        profitRecord.setUser(inviteUser);
        profitRecord.setChangeProfitType(ProfitRecord.ChangeProfitType.rakeBack);
        profitRecord.setProfitChangeType(ProfitRecord.ProfitChangeType.add);
        profitRecord.setChangeNum(userOrder.getPrice().multiply(returnCommission.getProportion()));
        profitRecord.setUserOrder(userOrder);
        profitRecordRepository.save(profitRecord);
        //积分比例
        //线上下单不送积分
       /* BigDecimal proportion = returnCommissionRepository.getBySysDeptAndDeletedFalseAndProportionType(inviteUser.getOrg(),ReturnCommission.ProportionType.integarl).getProportion();
        Integral integral = new Integral();
        integral.setUser(user);
        integral.setCiType(Integral.ChangeIntegralType.buyinteg);
        integral.setChangeType(Integral.ChangeType.add);
        integral.setChangeNum(userOrder.getPrice().multiply(proportion).longValue());
        integral.setUserOrder(userOrder);
        integralRepository.save(integral);*/
        userOrder.setStatus(UserOrder.UserOrderStatus.waitCheckOut);
        userOrderRepository.save(userOrder);
    }
}
